package com.lecing.ctrl;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.lecing.service.*;
import com.lecing.tpl.LcTplEngine;
import com.lecing.tpl.LcTplParser;
import com.lecing.utils.ExcelTpl;
import com.lecing.utils.ExcelUtil;
import com.lecing.utils.ExlsConstant;
import com.lecing.utils.StatData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * Excel生成控制器
 * Created by liucs on 2018/5/22.
 */
@Controller
@RequestMapping("/fc")
public class ExcelCtrl {
    Log log = LogFactory.getLog(ExcelCtrl.class);

    @Autowired
    private LedgerStat ledgerStat;

    @Autowired
    private RePayStat rePayStat;

    @Autowired
    private RefundStat refundStat;

    @Autowired
    private PayLoanStat payLoanStat; //月付/年付放款

    @Autowired
    private LoanTraCertStat loanTraCertStat; //放款交易凭证

    WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
    ServletContext servletContext = webApplicationContext.getServletContext();

    /*********************************乐醒财务月账**************************************************/
    @RequestMapping("/buildLedger")
    @ResponseBody
    public void buildMonLedger(HttpServletRequest request,HttpServletResponse response,String month){
        String tplPath= ExcelTpl.getTplPath(ExcelTpl.TplType.LEDGER); //获取月总账报表模板
        File file=new File(tplPath);
        //参数配置读取
        month=request.getParameter("month");
        // String destPath = "E:/out/月总账表("+month+").xlsx"; //输出文件
        String destPath = getOutFileStr(month, file,"outdir"); //输出文件路径
        log.info("====output file path=====:"+destPath);

        //1.获取请求参数，调用业务查询接口获取数据 暂且模拟
        Map<String,Object> ledgerMap= StatData.assemLedgerMapData(month);

        //2.调用模板引擎，解析模板变量,绑定数据生成excel
      //  ledgerMap.put("month",month);
        //LcTplEngine.genExcelFromTpl(tplPath,ledgerMap,destPath);
        boolean b= LcTplParser.parseData2Tpl(ledgerMap,tplPath,destPath,0);
        log.info("生成模板数据结果："+b);
        //下载
        downloadExcel(destPath,response);
    }

    /**
     * 生成月付放款
     * @param request
     * @param response
     * @param month
     * @return
     */
    @RequestMapping("/mPayLoan")
    @ResponseBody
    public String buildLoanExcel(HttpServletRequest request,HttpServletResponse response,String month){
        String res="";
        //获取请求参数
        month=request.getParameter("month"); //放款月次
        String flag=request.getParameter("flag");
        Map<String,String> map = new HashMap<>();
        map.put("month",month);
        map.put("rity","2001");

        Map<String, Object> objectMap = new HashMap<>();
        String tplPath=""; //tpl目录
        String destPath =""; //输出路径
        File file =null;
        List<Map<String, Object>> loanMapLst =null;
        if(flag.equals(ExlsConstant.FLAG_M_LOAN)) {//月付放款及明细
            tplPath = ExcelTpl.getTplPath(ExcelTpl.TplType.M_PAY_LOAN);
            file = new File(tplPath); //取得生成的文件路径
            destPath = getOutFileStr(month, file, "loan_path"); //输出文件路径

            loanMapLst = payLoanStat.queryMPayLoanLst(map);

            //2.调用模板引擎，解析模板变量,绑定数据生成excel
            objectMap.put("month", month);
            objectMap.put("mapList", loanMapLst);
            LcTplEngine.genExcelFromTpl(tplPath, objectMap, destPath);
        }
        if(flag.equals(ExlsConstant.FLAG_Y_LOAN)){  //年付放款及明细

        }
        log.info("====output file path=====:" + destPath);
        //下载Excel输出
        downloadExcel(destPath,response);
        return  res;
    }

    /**
     * 生成月付/年付还款 月报表
     * @param request
     * @param response
     * @param month
     */
    public void buildRepayExcl(HttpServletRequest request,HttpServletResponse response,String month){
        Map<String, Object> ledgerMap =null;

            String tplPath = ExcelTpl.getTplPath(ExcelTpl.TplType.M_PAY_REPAY); //获取月总账报表模板

            //获取请求参数
            month = request.getParameter("month");
            log.info("tplpath:" + tplPath);
            String destPath = "E:/out/月付还款表(" + month + ").xlsx"; //输出文件

            //1.获取请求参数，调用业务查询接口获取数据 暂且模拟
            ledgerMap = StatData.assemLedgerMapData(month);

        //2.封装map参数进行传递,调用模板引擎，解析模板，获取模板变量集合,绑定数据生成EXCEL表输出
        ledgerMap.put("month",month);
        LcTplEngine.genExcelFromTpl(tplPath,ledgerMap,destPath);

        //下载Excel输出
        downloadExcel(destPath,response);
    }

    /**
     * 下载生成过的Excel文件
     * @param exlsFile
     */
    private void downloadExcel(String exlsFile,HttpServletResponse response){
        InputStream fis =null;
        try{
            File newFile=new File(exlsFile);
            fis = new BufferedInputStream(new FileInputStream(newFile));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            response.setContentType("text/html;charset=UTF-8");
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/x-msdownload");
            String newName=exlsFile.substring(exlsFile.lastIndexOf("/")+1);
            String newName1 = URLEncoder.encode(newName, "UTF-8");

            String fileName= newName1.replace("%28","(").replace("%29",")");
            response.addHeader("Content-Disposition",
                    "attachment;filename=\"" + fileName + "\"");
            response.addHeader("Content-Length", "" + newFile.length());
            toClient.write(buffer);
            toClient.flush();
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
        }finally {
            try {
                if (null != fis) {
                    fis.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 得到输出文件字符串
     * @param date 日期/年月
     * @param file 输出文件
     * @param key 配置文件key
     * @return
     */
    private String getOutFileStr(String date, File file,String key) {
        String fname=file.getName();
        String oName=fname.substring(0,fname.lastIndexOf("."));
        String outPath= ExcelUtil.readPropsByKey(key);
        File outFile=new File(outPath);
        if (!outFile.exists()){
            outFile.mkdirs();
        }
        StringBuffer sb=new StringBuffer(outPath);
        sb.append(oName).append("(").append(date).append(")").append(".xlsx");
        return sb.toString();
    }
    /*********************************公寓月付还款**************************************************/

    /*********************************公寓年付还款**************************************************/

    /*********************************公寓月付违约返款**************************************************/

    /*********************************公寓年付违约返款**************************************************/

    /**===============================月付/年付 放款凭证及明细==================================================*/



}
